package com.by.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.by.demo.DruidDemo;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DruidUtils {
    public DruidUtils() {
    }
    //创建一个私有变量
    private static DataSource dataSource;
    static {
        //读取配置文件加载工厂类
        Properties prop=new Properties();
        try {
            prop.load(DruidUtils.class.getClassLoader().getResourceAsStream("druidConfig.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //提供一个链接对象方法
    public static Connection getConnection(){
        Connection conn=null;
        try {
            conn=dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    //提供一个链接池的方法
    public static DataSource getDataSource(){
        return dataSource;
    }
    //释放资源
    public static void close(Connection conn, Statement st, ResultSet rs){
        if(conn !=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st !=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs !=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection conn, Statement st){
        close(conn,st,null);
    }
}
